"use client";

import React from "react";
import { APILogin } from "@/app/api/login/login";
import { ResponseType } from "@/utils/types";
import "../app/style/login.css";
import { Form, Input, message } from "antd";
import { RiShieldUserFill } from "react-icons/ri";
import { IoIosLock } from "react-icons/io";
import { IoBarcode, IoCheckmarkDoneSharp } from "react-icons/io5";
import { MdConfirmationNumber } from "react-icons/md";
import SelButton from "@/componets/SelButton";
import { buttonType } from "@/componets/SelButton";
import { RiLoginCircleFill } from "react-icons/ri";
import { UserInfo } from "@/utils/types";
import { useEffect, useState } from "react";
import { UseAppSelector, UseAppDispatch } from "@/hooks/hook";
import {
  selectUsername,
  selectLoginStatus,
  login,
  LoginState,
} from "@/redux/loginStore";
import { useRouter } from "next/navigation";
import { Suspense } from "react";
import SkeletonLoading from "./SkeletonLoading";
import Cookies from "js-cookie";
import { MdOutlineWarningAmber } from "react-icons/md";
import { UserModalOp } from "./UserModal";

const loginInputStyle = {
  width: "250px",
  backgroundColor: "rgba(34, 62, 81, 0.7)",
  borderColor: "rgb(147, 197, 244)",
  color: "rgb(235, 223, 223)",
};

export default function Login({ children }: { children: React.ReactNode }) {
  //來決定切換到哪一個頁面--登錄信息存儲在redux中。登錄狀態只有2小時期限，故不需要存儲在localstorage中。
  //在服務器組件中獲取數據如果出現問題就跳轉到錯誤頁 error.tsx,error.tsx只包含當前路由內的頁面錯誤

  //登录页作为首页，使用服务端组件作为主页嵌套登录组件实在太复杂，不适合使用。
  const router = useRouter();
  const [messageApi, contextHolder] = message.useMessage();
  //登录按钮防抖，30秒之内点击一次，不能重复执行。
  const [frequency, Setfrequency] = useState(0);
  const [isLogin, setIsLogin] = useState(true);
  const dispatch = UseAppDispatch();
  const [userInfo, setUserInfo] = useState<UserInfo>({
    username: UseAppSelector(selectUsername),
    token: "",
    loginStatus: UseAppSelector(selectLoginStatus),
    password: "",
    confirm_password: "",
    captcha: "",
  });
  // const [openModal, setOpenModal] = useState(true);
  useEffect(() => {
    if (userInfo.loginStatus) {
      router.push("./dashboard");
    }
  }, [router, userInfo.loginStatus]);

  /**
   * @description:数据验证
   * :前端数据验证--相关正则验证。两项都成功后发送请求
   */
  const ValidDate = (): boolean => {
    if (!userInfo.username || !userInfo.password) {
      messageApi.warning("请输入用户名与密码");
      return false;
    }
    if (!userInfo.captcha) {
      messageApi.warning("请输入验证码");
      return false;
    }
    if (Cookies.get("captcha") !== userInfo.captcha) {
      messageApi.warning("你输入的验证码不正确，请重试！");
      return false;
    }
    //登录时验证
    if (isLogin) {
      if (userInfo.password.length < 8 || userInfo.username.length < 5) {
        messageApi.warning("密码长度不得低于8位，用户名长度不得低于5位");
        return false;
      }
    }
    return true;
  };

  /**
   * @description
   * :登录处理--30秒防抖机制防止频繁发起请求，造成资源乱用
   * :登录成功后，操作Redux，进入主页。登录失败，message提示
   */
  const LoginFunc = async () => {
    if (ValidDate()) {
      //登录防抖
      if (frequency) {
        messageApi.warning("你点击的太频繁，请稍后重试！");
        return false;
      }
      //启动，在请求发送后设置
      Setfrequency(1);
      //设置30S
      const timeMachine = setTimeout(() => {
        clearTimeout(timeMachine);
        Setfrequency(0);
      }, 10000);
      try {
        const res: ResponseType = await APILogin(
          userInfo.username.trim(),
          userInfo.password.trim(),
          "N"
        );
        setUserInfo({
          ...userInfo,
          token: res.data as unknown as string,
          loginStatus: true,
        });
        const LoginRedux: LoginState = {
          username: userInfo.username,
          token: res.data as unknown as string,
          loginStatus: true,
        };
        dispatch(login(LoginRedux));
        message.success("登录成功");
        router.push("./dashboard");
      } catch (err: any) {
        if (err.code === 202) {
          //setOpenModal(true)
          UserModalOp.open({
            conFirmText: "强制登录",
            cancelText: "取消",
            title: "提示",
            content: "此账号已在别的设备上登录，是否强制登录？",
            icon: MdOutlineWarningAmber,
            onConfirm: () => {
              UserModalOp.close();
              ForceLogin();
            },
            onCancel: () => {
              UserModalOp.close();
            },
          });
        } else {
          messageApi.error(err.message);
        }
      }
    } else {
      return false;
    }
  };

  /**
   * @description 强制登录
   */
  const ForceLogin = async () => {
    try {
      const res: ResponseType = await APILogin(
        userInfo.username.trim(),
        userInfo.password.trim(),
        "Y"
      );
      setUserInfo({
        ...userInfo,
        token: res.data as unknown as string,
        loginStatus: true,
      });
      const LoginRedux: LoginState = {
        username: userInfo.username,
        token: res.data as unknown as string,
        loginStatus: true,
      };
      dispatch(login(LoginRedux));
      message.success("登录成功");
      router.push("./dashboard");
    } catch (err: any) {
      messageApi.error(err.message);
    }
  };

  /**
   * @description:注册功能
   */
  const RegistFunc = () => {
    messageApi.info("注册功能开发中...");
    return false;
  };

  /**
   * @description:登录注册渲染，还可以根据排版进一步抽离相同的FormItem，目前排版不做优化
   */
  const LoginRender = () => {
    if (isLogin) {
      return (
        <>
          <Form.Item>
            <Suspense fallback={<SkeletonLoading></SkeletonLoading>}>
              {children}
            </Suspense>
          </Form.Item>
          <Form.Item>
            <Input
              placeholder="请输入验证码"
              type="text"
              prefix={<IoBarcode />}
              style={loginInputStyle}
              className="login-input-placeholder"
              maxLength={6}
              onChange={(e) => {
                setUserInfo({
                  ...userInfo,
                  captcha: e.target.value.toLocaleLowerCase().trim(),
                });
              }}
            ></Input>
          </Form.Item>
          <Form.Item style={{ paddingLeft: "50px" }}>
            <SelButton
              type={buttonType.leftSlide}
              text="登录"
              Icon={RiLoginCircleFill}
              height={34}
              color="rgba(34,118,174)"
              onClick={LoginFunc}
            ></SelButton>
          </Form.Item>
        </>
      );
    } else {
      return (
        <>
          <Form.Item>
            <Input.Password
              placeholder="确认密码"
              // type="text"
              prefix={<MdConfirmationNumber />}
              style={loginInputStyle}
              className="login-input-placeholder"
              maxLength={16}
              onChange={(e) => {
                setUserInfo({
                  ...userInfo,
                  confirm_password: e.target.value.trim(),
                });
              }}
              visibilityToggle={true}
            ></Input.Password>
          </Form.Item>
          <Form.Item>
            <Suspense fallback={<SkeletonLoading></SkeletonLoading>}>
              {children}
            </Suspense>
          </Form.Item>
          <Form.Item>
            <Input
              placeholder="请输入验证码"
              type="text"
              prefix={<IoBarcode />}
              style={loginInputStyle}
              className="login-input-placeholder"
              maxLength={6}
              onChange={(e) => {
                setUserInfo({
                  ...userInfo,
                  captcha: e.target.value.toLocaleLowerCase().trim(),
                });
              }}
            ></Input>
          </Form.Item>
          <Form.Item style={{ paddingLeft: "50px" }}>
            <SelButton
              type={buttonType.leftSlide}
              text="注册"
              Icon={IoCheckmarkDoneSharp}
              height={34}
              color="rgba(185, 58, 20)"
              onClick={RegistFunc}
            ></SelButton>
          </Form.Item>
        </>
      );
    }
  };

  return (
    <>
      {contextHolder}
      <div className="login-container">
        <div className="login-box">
          {/* 将登录与注册按照选择渲染 */}
          <Form style={{ paddingLeft: "50px", paddingTop: "30px" }}>
            <Form.Item>
              <Input
                placeholder="账号"
                type="text"
                prefix={<RiShieldUserFill />}
                style={loginInputStyle}
                className="login-input-placeholder"
                maxLength={16}
                onChange={(e) => {
                  setUserInfo({ ...userInfo, username: e.target.value.trim() });
                }}
              ></Input>
            </Form.Item>
            <Form.Item>
              <Input.Password
                placeholder="密码"
                // type="password"
                prefix={<IoIosLock />}
                style={loginInputStyle}
                maxLength={20}
                onChange={(e) => {
                  setUserInfo({ ...userInfo, password: e.target.value.trim() });
                }}
                visibilityToggle={true}
              ></Input.Password>
            </Form.Item>
            {LoginRender()}
            <Form.Item style={{ textAlign: "right", paddingRight: "15px" }}>
              <span
                className="span-click-return"
                onClick={() => {
                  setIsLogin(!isLogin);
                  setUserInfo({
                    username: "",
                    password: "",
                    confirm_password: "",
                    captcha: "",
                    loginStatus: false,
                    token: "",
                  });
                }}
              >
                {isLogin ? "没有账号？点我注册" : "已有账号？返回登录"}
              </span>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  );
}
